package model

import (
	"github.com/jinzhu/gorm"
)

type Resource struct {
	*Model
	Name         string `json:"name"`
	ChainName    string `json:"chain_name"`
	Username     string `json:"username"`
	ChainAccount string `json:"chain_account"`
	Price        int    `json:"price"`
	OnSale       int    `json:"on_sale"`
	Data         string `json:"data"`
}

func (r *Resource) TableName() string {
	return "resource"
}

func (r *Resource) Create(db *gorm.DB) error {
	return db.Create(r).Error
}

func (r *Resource) GetMy(db *gorm.DB) ([]*Resource, error) {
	var resources []*Resource
	err := db.Where("username = ? AND is_del = ?", r.Username, 0).Find(&resources).Error
	return resources, err
}

func (r *Resource) GetOnSale(db *gorm.DB) ([]*Resource, error) {
	var resources []*Resource
	err := db.Where("on_sale = ? AND is_del = ?", 1, 0).Find(&resources).Error
	return resources, err
}

func (r *Resource) Delete(db *gorm.DB, id int) error {
	return db.Where("id = ?", id).Delete(r).Error
}

func (r *Resource) Update(db *gorm.DB, id int, values map[string]interface{}) error {
	return db.Model(r).Where("id = ?", id).Update(values).Error
}
